package com.ruoyi.web.utils.qg_pay.utils;

import com.ruoyi.common.utils.BigDecimalUtils;
import com.ruoyi.framework.web.contants.AbnormalConstants;
import com.ruoyi.framework.web.enums.AbnormalEnum;
import com.ruoyi.framework.web.exception.TadpoleException;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.web.constant.LegalTenderCodeConstant;
import com.ruoyi.web.constant.SysConfigKeyConstant;
import com.ruoyi.web.utils.CommonUtil;
import com.ruoyi.web.utils.qg_pay.client.QGPayHttpClient;
import com.ruoyi.web.utils.qg_pay.config.QGPayConfig;
import com.ruoyi.web.utils.qg_pay.enums.QGPayParamEnum;
import lombok.AllArgsConstructor;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;

/**
 * QGPay工具类
 *
 * @since 2023/3/16 14:05
 */
@Component
@AllArgsConstructor
public class QGPayUtil {

    private final CommonUtil commonUtil;
    private final QGPayConfig qgConfig;
    private final ISysConfigService sysConfigService;

    /**
     * 代收时，获取银行编码
     *
     * @param legalTenderCode 法币编码
     * @param businessCode    业务编码
     * @since 2023/3/16 14:05
     */
    public static String getBankCodeWhenReceive(String legalTenderCode, String businessCode) {
        if (LegalTenderCodeConstant.IDR.equals(legalTenderCode) && "100034".equals(businessCode)) {
            return "BT";
        } else {
            return "BANK";
        }
    }

    /**
     * 根据汇率计算法币对应的USDT数量
     *
     * @param amount 法币额度
     * @param rate   对USDT（美元）汇率
     * @return {@link BigDecimal}
     * @since 2023/3/16 15:00
     */
    public static BigDecimal transferLegalTender2USDT(BigDecimal amount, BigDecimal rate) {
        return amount.divide(rate, 8, RoundingMode.HALF_UP);
    }

    /**
     * 根据汇率计算USDT数量对应的法币
     *
     * @param usdt USDT数量
     * @param rate 对USDT（美元）汇率
     * @return {@link BigDecimal}
     * @since 2023/3/16 15:00
     */
    public static BigDecimal transferUSDT2LegalTender(BigDecimal usdt, BigDecimal rate) {
        return usdt.multiply(rate);
    }

    /**
     * 校验通知
     *
     * @param obj 对象
     * @since 2023/3/17 14:12
     */
    public void validNotify(Object obj) {
        Map<String, Object> treeMap = new TreeMap<>(Comparator.naturalOrder());
        String json = commonUtil.toJson(obj);
        HashMap<String, Object> bodyMap = commonUtil.parseJson(json, HashMap.class);
        // 获取签名
        Object signatureObj = bodyMap.get(QGPayParamEnum.SIGN.getName());
        if (Objects.isNull(signatureObj)) {
            throw new TadpoleException(AbnormalConstants.MANDATORY_PARAM_EMPTY_OR_MALFORMED);
        }

        String signature = signatureObj.toString();
        if (Strings.isBlank(signature)) {
            throw new TadpoleException(AbnormalConstants.MANDATORY_PARAM_EMPTY_OR_MALFORMED);
        }
        // 将签名从参数中移除
        bodyMap.put(QGPayParamEnum.SIGN.getName(), null);
        // 清除为空的参数
        QGPayHttpClient.clearEmptyParam(bodyMap);
        treeMap.putAll(bodyMap);

        String encryptSrc = QGPayHttpClient.getEncryptSrc(treeMap);
        String signatureSrc = RsaUtil.decryptByPublic(signature, qgConfig.getPublicKey());

        // 如果不一致，抛出异常
        if (!encryptSrc.equals(signatureSrc)) {
            throw new TadpoleException(AbnormalEnum.MSG.UNKNOWN_ORDER_COMPOSITION);
        }
    }

    /**
     * 获取提现手续费率
     *
     * @return {@link BigDecimal}
     * @since 2023/3/23 16:44
     */
    public BigDecimal getWithdrawalFeeRate() {
        String feeRateStr = sysConfigService.selectConfigByKey(SysConfigKeyConstant.LEGAL_TENDER_WITHDRAWAL_FEE_RATE);
        return BigDecimalUtils.toPercent(Strings.isBlank(feeRateStr) ? BigDecimal.ONE : BigDecimal.valueOf(Double.parseDouble(feeRateStr)));
    }
}
